<?php

// +----------------------------------------------------------------------
// | 任务
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\common\event;

use app\pay\event\UserBalanceCash as UserBalanceCashEvent;
use app\common\model\Job as JobModel;
use think\Loader;

class Job extends Base
{


    /**
     * 添加任务
     * /**
     * @param string $name
     * @param array|$data [] $data
     * @param int|string $delay
     * @param int|string $grace 宽限最晚执行时间
     * @return mixed
     */
    public static function addTask(string $name, $data = [], $delay = 0, $grace = 3600)
    {
        $job = JobModel::where('name', $name)->where('status', 1)->find();
        if ($job) {
            $reserved_time = self::_getQps($job, $delay, $grace);
            if ($job['reserved_start_time'] > $reserved_time || empty($job['reserved_start_time'])) {
                $job['reserved_start_time'] = $reserved_time;
            }
            if (!is_int($grace)) {
                $grace = strtotime($grace) - time();
            }
            $grace_time = time_format(strtotime($reserved_time) + $grace);
            if ($job['reserved_end_time'] < $grace_time || empty($job['reserved_end_time'])) {
                $job['reserved_end_time'] = $grace_time;
            }
            $job['reserved'] = 1;
            $job->save();
            $task = [];
            $task['data'] = $data;
            $task['available'] = 1;
            $task['reserved_time'] = $reserved_time;
            $job->tasks()->save($task);
        }
        return $job;
    }


    protected static function _getQps($job, $delay, $grace): string
    {
        $reserved_time = is_int($delay) ? time_format(time() + $delay) : time_format(strtotime($delay));
        if ($job['qps'] > 0) {
            $count = $job->tasks()->where('reserved_time', $reserved_time)->where('available', 1)->count();
            if ($count >= $job['qps']) {
                return self::_getQps($job, $delay + 1, $grace);
            }
        }
        return $reserved_time;
    }
}
